﻿using System.Linq;
using System.Web.Mvc;
using Citi.GocAttributes.Domain;

namespace Citi.GocAttributes.WebUI.Controllers
{
    public class ManagedSegmentController : Controller
    {
        [HttpGet]
        public JsonResult GetAutocomplete(string searchTerm, int level)
        {
            var managedSegments = new ManagedSegment().SelectAllActive<ManagedSegment>()
                            .Where(x => x.TreeLevel == level && (x.Code.ToString().ToUpper().Contains(searchTerm.ToUpper())
                                || x.Description.ToUpper().Contains(searchTerm.ToUpper())))
                            .GroupBy(c => c.Code)
                            .Select(g => g.OrderByDescending(c => c.ReferenceDate).First())
                            .Select(c => new { c.Code, c.Id, c.Description });

            return Json(managedSegments.Select(x => new
                {
                    x.Id,
                    Description = string.Concat(x.Code, " - ", x.Description)
                }),
                JsonRequestBehavior.AllowGet);
        }
    }
}
